﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vowei.Data.Models;
using Vowei.Core.Models;
using Vowei.Data;
using Vowei.Core.Scm;
using System.Text;
using System.Text.RegularExpressions;
using Vowei.Web.Models;
using Autofac;
using Vowei.Data.Helpers;
using Vowei.Web.Helpers;

namespace Vowei.Web.Controllers
{
    [HandleError]
    public class CommentController : G18nController
    {
        private SvnLogFormatter _formatter = new SvnLogFormatter();
        private IVoweiContext _context;
        private IUser _user;

        public CommentController(IVoweiContext context, IUser user)
        {
            _context = context;
            _user = user;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Comment comment)
        {
            comment.User = ViewHelpers.GetLogonUserName();
            _context.Comments.Add(comment);

            switch (comment.PostType)
            {
                case "Requirement":
                case "Ticket":
                case "Bug":
                case "Task":
                    var task = _context.Tickets.Find(comment.PostId);
                    task.Comments.Add(comment);
                    break;

                case "Project":
                case "Milestone":
                    var milestone = _context.Milestones.Find(comment.PostId);
                    milestone.Comments.Add(comment);
                    break;

                default:
                    throw new InvalidOperationException(string.Format(T("不支持对 {0} 类型实现评论功能"), comment.PostType));
            }

            _context.SaveChanges();

            return Json(comment);
        }

        [HttpPost]
        public ActionResult PostComments(Comment[] comments)
        {
            if (comments.Length > 0)
            {
                var ticket = _context.Tickets.Find(comments[0].PostId);
                if (ticket == null)
                {
                    throw new InvalidOperationException(
                        string.Format(T("找不到ID为{0}的任务！"), comments[0].PostId));
                }

                Project project = (Project)EntityHelpers.FindProjectFor(ticket, _context);
                if (project == null)
                {
                    throw new InvalidOperationException(
                        string.Format(T("ID为{0}的任务没有对应的项目与其关联！"), comments[0].PostId));
                }

                var changeset = new List<ChangeSet>();

                foreach (var comment in comments)
                {
                    string changedFiles;
                    string changeName;
                    var commentText = FixCommentFormat(comment, project, out changeName, out changedFiles);
                    comment.Text = commentText;
                    _context.Comments.Add(comment);

                    ticket = _context.Tickets.Find(comment.PostId);
                    ticket.Comments.Add(comment);
                    _context.TicketStatusManager.Close(ticket);

                    if (!string.IsNullOrEmpty(changeName))
                    {
                        var change = changeset.SingleOrDefault(c => c.Title == changeName);
                        if (change == null)
                        {
                            change = new ChangeSet()
                            {
                                Title = changeName,
                                Project = project,
                                ChangedFileList = changedFiles
                            };
                            changeset.Add(change);
                            _context.ChangeSet.Add(change);
                        }

                        change.Tickets.Add(ticket);
                    };
                }

                _context.SaveChanges();
            }

            return WebConstants.HttpSuccess;
        }

        private string FixCommentFormat(Comment c, Project project, out string changeId, out string changedFiles)
        {
            var text = c.Text;
            changeId = null;
            changedFiles = null;
            var idxFilelist = text.LastIndexOf("\n\n");

            if (idxFilelist >= 0)
            {
                var actualCommentTxt = text.Substring(0, idxFilelist);
                actualCommentTxt = actualCommentTxt.Replace("\n", "<BR />");
                var fileListTxt = text.Substring(idxFilelist + 2, text.Length - idxFilelist - 2);
                var idReg = new Regex(@"\[(\d+)\]");
                var match = idReg.Match(actualCommentTxt);

                if (match.Success)
                {
                    changeId = match.Groups[1].Value;
                    actualCommentTxt = idReg.Replace(actualCommentTxt,
                        string.Format("<a href=/scm/details/?name={0}&milestone={1}>[{0}]</a>", changeId, project.ID));
                }

                var list = _formatter.FormatChangedLog(fileListTxt, project);
                var builder = new StringBuilder();

                foreach (var f in list)
                {
                    builder.Append(f);
                    builder.Append("<BR />");
                }

                changedFiles = builder.ToString();

                return actualCommentTxt;
            }
            else
                return null;
        }
    }
}
